<template>
  <div class="header-container">
    <div class="left-section">
      <!-- 改进：根据路由历史智能显示返回按钮 -->
      <el-icon v-if="showBackButton" class="back-button" @click="handleBack">
        <Back/>
      </el-icon>
      <!-- 改进：动态页面标题，使用路由元信息 -->
      <span class="page-title">{{ pageTitle }}</span>
    </div>

    <div class="right-section">
      <!-- 改进：添加点击事件和触摸设备支持 -->
      <div class="user-profile"
           @click.stop="toggleDropdown"
           @mouseenter="showDropdown = true"
           @mouseleave="showDropdown = false">
        <!-- 改进：添加图片加载失败处理 -->
        <img
            :src="userAvatar"
            class="user-avatar"
            alt="用户头像"
            @error="handleImageError"
        />

        <!-- 改进：下拉菜单增加边界检测 -->
        <transition name="dropdown-transition">
          <div v-show="showDropdown"
               class="dropdown-menu"
               :class="{ 'dropdown-up': needPositionUp }">
            <div class="user-info-item">
              <span class="info-label">账号：</span>
              {{ userAccount }}
            </div>
            <div class="user-info-item">
              <span class="info-label">姓名：</span>
              {{ userName }}
            </div>
            <el-divider class="info-divider"/>
            <div class="logout-item" @click="handleLogout">
              <el-icon class="logout-icon">
                <SwitchButton/>
              </el-icon>
              安全退出
            </div>
          </div>
        </transition>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, computed, onMounted, onBeforeUnmount, watch} from 'vue'
import {useRouter, useRoute} from 'vue-router'
import {ElMessage} from 'element-plus'
import {SwitchButton, Back} from '@element-plus/icons-vue'
import {useStore} from 'vuex'
import {getLoginerInfo, logout} from '../service/userApi'
import defaultAvatar from '../assets/images/default.jpeg' // 改进：使用别名路径

const router = useRouter()
const route = useRoute()
const store = useStore()

// 响应式状态
const state = reactive({
  userInfo: null,
  dropdownPositionUp: false
})

const showDropdown = ref(false)
const lastScrollPosition = ref(0)

// 计算属性改进
const userAccount = computed(() => state.userInfo?.loginUserName || '未登录')
const userName = computed(() => state.userInfo?.realName || '游客')
const userAvatar = computed(() => state.userInfo?.headUrl || defaultAvatar)
const pageTitle = computed(() => route.meta.title || '管理平台')
const showBackButton = computed(() => router.options.history.state.back !== null)

// 改进：自动检测下拉菜单位置
const needPositionUp = computed(() => {
  const viewportHeight = window.innerHeight
  const avatarBottom = document.querySelector('.user-profile')?.getBoundingClientRect().bottom || 0
  return avatarBottom > viewportHeight * 0.7
})

// 改进：添加全局点击监听
const handleClickOutside = (event) => {
  if (!event.target.closest('.user-profile')) {
    showDropdown.value = false
  }
}

onMounted(() => {
  // 改进：通过路由守卫控制用户信息获取
  if (store.getters.isAuthenticated) {
    fetchUserInfo()
  }
  document.addEventListener('click', handleClickOutside)
  window.addEventListener('scroll', handleScroll)
})

onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside)
  window.removeEventListener('scroll', handleScroll)
})

// 改进：滚动处理优化
const handleScroll = () => {
  const currentPosition = window.scrollY
  if (Math.abs(currentPosition - lastScrollPosition.value) > 50) {
    showDropdown.value = false
  }
  lastScrollPosition.value = currentPosition
}

// 改进：添加图片加载失败处理
const handleImageError = (e) => {
  e.target.src = defaultAvatar
}

// 改进：用户信息获取逻辑
const fetchUserInfo = async () => {
  const response = await getLoginerInfo();
  state.userInfo = {
    loginUserName: response.data.username,
    realName: response.data.name,
    headUrl: response.data.avatar || defaultAvatar
  }
}

const handleLogout = async () => {
  // 先清后端
  await logout()
  // 再清前端
  await store.dispatch('logout')
  // 最后进行跳转
  await router.replace({path: '/login', query: {redirect: route.fullPath}})
  ElMessage.success('已安全退出')
}

// 改进：下拉菜单切换逻辑
const toggleDropdown = () => {
  showDropdown.value = !showDropdown.value
}

// 改进：返回按钮逻辑增强
const handleBack = () => {
  if (route.meta?.keepAlive) {
    router.back()
  } else {
    router.push('/')
  }
}
</script>

<style scoped>
/* 重构后的标准CSS方案 */
.header-container {
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  background: #ffffff;
  border-bottom: 1px solid #ebeef5;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.left-section {
  display: flex;
  align-items: center;
  gap: 16px;
}

.back-button {
  font-size: 1.25rem;
  color: #606266;
  cursor: pointer;
  transition: color 0.3s;
}

.back-button:hover {
  color: #409eff;
}

.page-title {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.user-profile {
  position: relative;
  cursor: pointer;
}

.user-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  border: 2px solid #fff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
}

.user-avatar:hover {
  transform: scale(1.08);
}

.dropdown-menu {
  position: absolute;
  right: 0;
  top: 48px;
  width: 240px;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  z-index: 9999;
  padding: 12px 0;
}

.dropdown-menu.dropdown-up {
  bottom: 100%;
  top: auto;
  margin-bottom: 8px;
}

.user-info-item {
  padding: 8px 20px;
  font-size: 14px;
  color: #606266;
  display: flex;
  align-items: center;
  transition: background-color 0.3s;
}

.user-info-item:hover {
  background-color: #f5f7fa;
}

.info-label {
  color: #909399;
  min-width: 60px;
  display: inline-block;
}

.info-divider {
  margin: 8px 0;
  border-color: #ebeef5;
}

.logout-item {
  padding: 8px 20px;
  color: #f56c6c;
  display: flex;
  align-items: center;
  transition: background-color 0.3s;
}

.logout-item:hover {
  background-color: #fef0f0;
}

.logout-icon {
  margin-right: 8px;
  font-size: 16px;
}

/* 下拉动画 */
.dropdown-transition-enter-active {
  animation: dropdown-in 0.25s ease-out;
}

.dropdown-transition-leave-active {
  animation: dropdown-out 0.2s ease-in;
}

@keyframes dropdown-in {
  0% {
    opacity: 0;
    transform: translateY(-10px);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes dropdown-out {
  0% {
    opacity: 1;
    transform: translateY(0);
  }
  100% {
    opacity: 0;
    transform: translateY(-10px);
  }
}
</style>